package poswar.contribute.mbean;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import org.primefaces.model.tagcloud.DefaultTagCloudItem;
import org.primefaces.model.tagcloud.DefaultTagCloudModel;
import org.primefaces.model.tagcloud.TagCloudModel;

@ManagedBean
@ApplicationScoped
public class CloudBean {
	private Map<String, String> ideas = new HashMap<String, String>();
	private TagCloudModel cloudModel;
	private int max;
	
	public int getMax() {
		return max;
	}

	public void setMax(int max) {
		this.max = max;
	}

	@PostConstruct
	private void init() {
		cloudModel = new DefaultTagCloudModel();
	}

	public void buildCloudModel() {
		cloudModel.clear();

		LinkedList<String> allIdeas = new LinkedList<String>();
		for (String email : ideas.keySet()) {
			String lines[] = ideas.get(email).split("\\r?\\n");
			List<String> list = Arrays.asList(lines);
			if (max != 0 && list.size() > max) {
				list = list.subList(0, max);
			}
			allIdeas.addAll(list);
		}

		Map<String, Integer> countMap = new HashMap<String, Integer>();

		int max = 0;
		for (String s : allIdeas) {

			Integer count = countMap.get(s);
			if (count == null) {
				count = 0;
			}
			countMap.put(s, ++count);
			if (count > max) {
				max = count;
			}
		}

		for (String s : countMap.keySet()) {
			if ("".equals(s.trim()))
				continue;
			
 			int counts = countMap.get(s);
			double weight = ((double) counts / (double) max) * 4 + 1;
			cloudModel.addTag(new DefaultTagCloudItem(s, (int) Math
					.round(weight)));
		}
	}

	public TagCloudModel getCloudModel() {
		return cloudModel;
	}
	
	public String setIdea(String email, String idea) {
		ideas.put(email, idea);
		buildCloudModel();
		
		return idea;
	}	
	
	public int getNumOfIdeas() {
		return ideas.size();
	}

	public String reset() {
		ideas.clear();
		cloudModel.clear();
		return null;
	}
}
